<template>
  <div class="map-container" id="container" ref="mapContainer"></div>
  <div v-if="isMarkersLoading" class="loading-overlay">
    <van-loading color="#1989fa" />
    <span>加载中...</span>
  </div>
  <div class="map-tips">
    <p>提示: 蓝色标记为您的位置，点击用户头像标记可查看详细信息</p>
  </div>
  <div v-if="showRouteInfo" class="route-info">
    <div class="route-info-header">
      <span>路线信息</span>
      <van-icon name="cross" @click="closeRouteInfo" />
    </div>
    <div class="route-info-content">
      <p><van-icon name="location" /> 距离：{{ routeDistance }} 公里</p>
      <p><van-icon name="clock" /> 预计时间：{{ routeDuration }}</p>
      <p v-if="routeTarget"><van-icon name="friends" /> 目标用户：{{ routeTarget }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, defineProps, defineEmits, watch, onActivated } from 'vue';
import { showToast } from 'vant';
import { UserType } from "../../models/user";
import { processImageUrl } from '../../utils/imageUtils';
import myAxios from '../../plugins/myAxios';

// 确保TypeScript能够识别全局AMap
declare global {
  interface Window {
    AMap: {
      Map: any;
      Marker: any;
      Icon: any;
      Size: any;
      Pixel: any;
      LngLat: any;
      InfoWindow: any;
      Scale: any;
      ToolBar: any;
      ControlBar: any;
      plugin: any;
      Bounds: any;
      Animation: {
          BOUNCE: string;
          DROP: string;
          NONE: string;
      };
      Driving: any;
      DrivingPolicy: {
          LEAST_TIME: number;
          LEAST_DISTANCE: number;
          LEAST_FEE: number;
          REAL_TRAFFIC: number;
      };
    }; // 使用any类型避免类型冲突
  }
}

// 定义组件属性
const props = defineProps<{
  userList: UserType[];
  loading: boolean;
}>();

const emit = defineEmits(['clickUser']);

// 引用和状态
const mapContainer = ref<HTMLElement | null>(null);
const map = ref<any>(null);
const markers = ref<any[]>([]);
const infoWindows = ref<any[]>([]);
const isMarkersLoading = ref(false);
const currentUser = ref<UserType | null>(null);
const currentUserMarker = ref<any>(null);

// 新增路线规划相关状态
const drivingInstance = ref<any>(null);
const showRouteInfo = ref(false);
const routeDistance = ref('');
const routeDuration = ref('');
const routeTarget = ref('');

// 初始化地图
const initMap = () => {
  if (!window.AMap) {
    console.error('高德地图API未加载');
    showToast('高德地图加载失败');
    return;
  }

  try {
    // 创建地图
    map.value = new window.AMap.Map('container', {
      zoom: 13,
      viewMode: '2D',
      center: [114.3619, 30.53860], // 默认武汉中心
      resizeEnable: true,
      doubleClickZoom: true,
      scrollWheel: true,
      showBuildingBlock: true,
      mapStyle: 'amap://styles/normal'
    });

    // 加载坐标转换插件
    window.AMap.plugin('AMap.Geolocation', () => {
      console.log('地图坐标转换插件加载成功');
    });

    // 添加控件
    if (window.AMap.Scale) {
      map.value.addControl(new window.AMap.Scale());
    }
    
    if (window.AMap.ToolBar) {
      map.value.addControl(new window.AMap.ToolBar({
        position: 'RB',
        liteStyle: false
      }));
    }
    
    console.log('地图初始化完成');
  } catch (error) {
    console.error('地图初始化失败:', error);
    showToast('地图初始化失败：' + (error instanceof Error ? error.message : String(error)));
    throw error; // 重新抛出错误，让调用者处理
  }
};

// 坐标系转换函数
const convertCoordinates = (lng: number, lat: number) => {
  // 简单转换，WGS84 转 GCJ02
  if (outOfChina(lng, lat)) {
    return { lng, lat };
  }
  
  const PI = Math.PI;  // 使用JavaScript内置的π值
  const a = 6378245.0;
  const ee = 0.00669342162296594;  // 减少不必要的小数位
  
  let dlat = transformLat(lng - 105.0, lat - 35.0);
  let dlng = transformLng(lng - 105.0, lat - 35.0);
  
  const radlat = lat / 180.0 * PI;
  let magic = Math.sin(radlat);
  magic = 1 - ee * magic * magic;
  
  const sqrtmagic = Math.sqrt(magic);
  dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
  dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
  
  const mglat = lat + dlat;
  const mglng = lng + dlng;
  
  return { lng: mglng, lat: mglat };
};

// 坐标转换辅助函数
const transformLat = (lng: number, lat: number) => {
  let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
  ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (160.0 * Math.sin(lat / 12.0 * Math.PI) + 320 * Math.sin(lat * Math.PI / 30.0)) * 2.0 / 3.0;
  return ret;
};

const transformLng = (lng: number, lat: number) => {
  let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
  ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (150.0 * Math.sin(lng / 12.0 * Math.PI) + 300.0 * Math.sin(lng / 30.0 * Math.PI)) * 2.0 / 3.0;
  return ret;
};

// 判断坐标是否在中国境外
const outOfChina = (lng: number, lat: number) => {
  return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
};

// 获取用户纬度的辅助函数
const getUserLatitude = (user: UserType): number | undefined => {
  return user.dimension;
};

// 创建用户标记的辅助函数
const createUserMarker = (user: UserType) => {
  const userLat = getUserLatitude(user);
  if (!user.longitude || !userLat) return null;
  
  // 转换坐标
  const converted = convertCoordinates(user.longitude, userLat);
  const position = new window.AMap.LngLat(converted.lng, converted.lat);
  
  // 创建标记
  const marker = new window.AMap.Marker({
    position,
    title: user.username,
    icon: new window.AMap.Icon({
      size: new window.AMap.Size(40, 40),
      image: processImageUrl(user.avatarUrl) || 'https://img.yzcdn.cn/vant/cat.jpeg',
      imageSize: new window.AMap.Size(40, 40)
    }),
    offset: new window.AMap.Pixel(-20, -40),
    clickable: true,
    zooms: [3, 20],
    animation: 'AMAP_ANIMATION_DROP'
  });
  
  return { marker, position, user };
};

// 创建信息窗口内容
const createInfoWindowContent = (user: UserType) => {
  return `
    <div class="map-info-window" style="border-radius:10px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,0.15);background:white;width:240px;">
      <div style="display:flex;padding:12px;">
        <img src="${processImageUrl(user.avatarUrl) || 'https://img.yzcdn.cn/vant/cat.jpeg'}" 
            style="width:50px;height:50px;border-radius:50%;border:3px solid #1989fa;object-fit:cover;">
        <div style="margin-left:10px;flex:1;">
          <h3 style="margin:0 0 5px 0;font-size:16px;color:#333;">${user.username || '未知用户'}</h3>
          <p style="margin:0 0 5px 0;color:#666;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${user.profile || '这个人很懒，什么都没写'}</p>
          <p style="margin:0 0 8px 0;color:#1989fa;font-size:13px;font-weight:bold;">距离: ${user.distance ? user.distance.toFixed(2) + ' km' : '未知'}</p>
          <div style="display:flex;gap:8px;">
            <button id="view-user-btn" style="flex:1;background:#1989fa;color:white;border:none;padding:8px 0;border-radius:4px;font-size:14px;cursor:pointer;font-weight:bold;">查看详情</button>
            <button id="plan-route-btn" style="flex:1;background:#07c160;color:white;border:none;padding:8px 0;border-radius:4px;font-size:14px;cursor:pointer;font-weight:bold;">规划路线</button>
          </div>
        </div>
      </div>
    </div>
  `;
};

// 为标记附加信息窗口和事件
const attachInfoWindowAndEvents = (markerInfo) => {
  const { marker, user } = markerInfo;
  
  // 创建信息窗口
  const infoContent = createInfoWindowContent(user);
  const infoWindow = new window.AMap.InfoWindow({
    content: infoContent,
    offset: new window.AMap.Pixel(0, -50)
  });
  
  // 绑定点击事件
  marker.on('click', () => {
    infoWindows.value.forEach(window => window.close());
    infoWindow.open(map.value, marker.getPosition());
    
    // 绑定查看详情按钮点击事件
    setTimeout(() => {
      const viewBtn = document.getElementById('view-user-btn');
      const planRouteBtn = document.getElementById('plan-route-btn');
      
      if (viewBtn) {
        viewBtn.addEventListener('click', () => {
          emit('clickUser', user.id);
          infoWindow.close();
        });
      }
      
      if (planRouteBtn && currentUser.value) {
        planRouteBtn.addEventListener('click', () => {
          planRoute(user);
          infoWindow.close();
        });
      }
    }, 100);
  });
  
  infoWindows.value.push(infoWindow);
  return marker;
};

// 创建地图边界
const createBoundsForMarkers = (userMarkers) => {
  let bounds = new window.AMap.Bounds();
  
  // 添加所有用户标记到边界
  userMarkers.forEach(marker => {
    bounds.extend(marker.getPosition());
  });
  
  // 如果当前用户标记存在，将其位置也包含在边界内
  if (currentUserMarker.value) {
    const currentUserPosition = currentUserMarker.value.getPosition();
    if (currentUserPosition) {
      bounds.extend(currentUserPosition);
    }
  }
  
  return bounds;
};

// 处理空用户列表情况
const handleEmptyUserList = () => {
  isMarkersLoading.value = false;
  
  // 如果没有其他用户，但当前用户有标记，则设置地图中心为当前用户位置
  if (currentUserMarker.value && map.value) {
    const position = currentUserMarker.value.getPosition();
    if (position) {
      map.value.setCenter(position);
      map.value.setZoom(15); // 设置适当的缩放级别
    }
  }
};

// 添加用户标记 - 重构后的主函数
const addMarkers = () => {
  isMarkersLoading.value = true;
  clearMarkers();
  
  // 过滤有效的用户（有经纬度信息且不是当前用户）
  const validUsers = props.userList.filter(user => 
    user.longitude && user.dimension && 
    (!currentUser.value || user.id !== currentUser.value.id)
  );
  
  if (validUsers.length === 0) {
    handleEmptyUserList();
    return;
  }
  
  // 第一步：创建所有标记
  const markerInfoList = validUsers
    .map(user => createUserMarker(user))
    .filter(Boolean);
  
  // 第二步：为每个标记添加信息窗口和事件处理
  const userMarkers = markerInfoList
    .map(markerInfo => attachInfoWindowAndEvents(markerInfo));
  
  // 第三步：将所有标记添加到地图
  if (userMarkers.length > 0) {
    map.value.add(userMarkers);
    markers.value = userMarkers;
    
    // 第四步：调整地图视图以包含所有标记
    const bounds = createBoundsForMarkers(userMarkers);
    map.value.setBounds(bounds, false, [50, 50, 50, 50]);
  }
  
  isMarkersLoading.value = false;
};

// 清除所有标记和信息窗体
const clearMarkers = () => {
  markers.value.forEach(marker => {
    marker.setMap(null);
  });
  
  infoWindows.value.forEach(infoWindow => {
    infoWindow.close();
  });
  
  markers.value = [];
  infoWindows.value = [];
};

// 添加或更新当前用户标记
const addOrUpdateCurrentUserMarker = async () => {
  // 获取当前用户最新信息，确保头像URL是最新的
  try {
    const updatedUserRes = await myAxios.get('/user/current');
    if (updatedUserRes?.code === 0 && currentUser.value) {
      // 更新当前用户数据，确保使用最新的头像URL
      Object.assign(currentUser.value, updatedUserRes.data);
    } else if (updatedUserRes?.code === 0) {
      // 如果当前用户为null，直接设置
      currentUser.value = updatedUserRes.data;
    }
  } catch (error) {
    console.error('获取最新用户信息失败', error);
  }

  if (!currentUser.value || !map.value) return;
  
  // 从这里开始复制showCurrentUserLocation函数中创建标记的代码
  if (currentUserMarker.value) {
    console.log('清除之前的用户标记');
    currentUserMarker.value.setMap(null);
    currentUserMarker.value = null;
  }
  
  let lng, lat;
  
  if (currentUser.value.longitude && currentUser.value.dimension) {
    console.log('使用用户的经纬度信息:', currentUser.value.longitude, currentUser.value.dimension);
    lng = currentUser.value.longitude;
    lat = currentUser.value.dimension;
    
    // 坐标转换 - WGS84 转 GCJ02
    const convertedCoords = convertCoordinates(lng, lat);
    lng = convertedCoords.lng;
    lat = convertedCoords.lat;
    console.log('转换后的坐标:', lng, lat);
  } else {
    console.log('用户没有坐标信息，使用地图中心点作为默认位置');
    const center = map.value.getCenter();
    lng = center.lng;
    lat = center.lat;
    console.log('使用地图中心点:', lng, lat);
    
    // 提示用户更新个人位置
    showToast({
      message: '您尚未设置位置信息，请到个人中心更新位置',
      position: 'bottom',
      duration: 5000
    });
  }
  
  const position = new window.AMap.LngLat(lng, lat);
  console.log('创建用户位置标记在:', position);
  
  try {
    // 创建带文本的标记
    const markerContent = document.createElement('div');
    markerContent.className = 'custom-marker current-user-marker';
    
    markerContent.innerHTML = `
      <div class="marker-image" style="
        background-image: url(${processImageUrl(currentUser.value.avatarUrl) || 'https://img.yzcdn.cn/vant/cat.jpeg'});
        background-size: cover;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        border: 4px solid #1989fa;
        box-shadow: 0 0 15px rgba(25, 137, 250, 0.8);
        margin: 0 auto;
      "></div>
      <div class="marker-name" style="
        background-color: #1989fa;
        color: white;
        padding: 3px 10px;
        border-radius: 12px;
        font-size: 14px;
        font-weight: bold;
        margin-top: 4px;
        text-align: center;
        white-space: nowrap;
        transform: translateY(-50%);
      ">
        <span>🔵 我的位置</span>
      </div>
    `;
    
    // 创建当前用户标记
    currentUserMarker.value = new window.AMap.Marker({
      position,
      content: markerContent,
      title: `当前用户: ${currentUser.value.username}`,
      offset: new window.AMap.Pixel(0, 0),
      anchor: 'center',
      zIndex: 1000,
      animation: 'AMAP_ANIMATION_DROP',
      extData: {
        type: 'currentUser',
        userId: currentUser.value.id
      }
    });
    
    // 创建当前用户信息窗体
    const infoWindow = new window.AMap.InfoWindow({
      content: `
        <div class="user-card current-user-card" style="
          padding: 15px;
          border-radius: 10px;
          box-shadow: 0 2px 12px rgba(0,0,0,0.1);
          max-width: 300px;
        ">
          <div class="user-header" style="
            display: flex;
            align-items: center;
            margin-bottom: 10px;
          ">
            <img src="${processImageUrl(currentUser.value.avatarUrl) || 'https://img.yzcdn.cn/vant/cat.jpeg'}" 
                 alt="${currentUser.value.username}" 
                 style="width:50px;height:50px;border-radius:50%;border:3px solid #1989fa;object-fit:cover;">
            <div style="margin-left:10px;">
              <div style="font-weight:bold;font-size:16px;color:#333;">${currentUser.value.username} (当前用户)</div>
              <div style="color:#666;font-size:13px;">${currentUser.value.profile || '这个人很懒，什么都没写'}</div>
            </div>
          </div>
          <div style="font-size:14px;color:#666;margin-bottom:10px;">
            <p style="margin:5px 0;">经度: ${currentUser.value.longitude || '未设置'}</p>
            <p style="margin:5px 0;">纬度: ${currentUser.value.dimension || '未设置'}</p>
          </div>
          <button id="view-profile-btn" style="
            width:100%;
            background:#1989fa;
            color:white;
            border:none;
            padding:8px 0;
            border-radius:4px;
            font-size:14px;
            cursor:pointer;
            font-weight:bold;
          ">查看个人主页</button>
          <button id="update-profile-btn" style="
            width:100%;
            background:#07c160;
            color:white;
            border:none;
            padding:8px 0;
            border-radius:4px;
            font-size:14px;
            cursor:pointer;
            font-weight:bold;
            margin-top: 8px;
          ">更新个人信息</button>
        </div>
      `,
      offset: new window.AMap.Pixel(0, -30)
    });
    
    // 点击当前用户标记时展示信息窗体
    currentUserMarker.value.on('click', () => {
      infoWindows.value.forEach(window => window.close());
      infoWindow.open(map.value, position);
      
      // 添加按钮点击事件处理器
      setTimeout(() => {
        const viewProfileBtn = document.getElementById('view-profile-btn');
        if (viewProfileBtn && currentUser.value) {
          viewProfileBtn.addEventListener('click', () => {
            emit('clickUser', currentUser.value!.id);
            infoWindow.close();
          });
        }
        
        const updateProfileBtn = document.getElementById('update-profile-btn');
        if (updateProfileBtn) {
          updateProfileBtn.addEventListener('click', () => {
            window.location.href = `${window.location.origin}/user/update`;
            infoWindow.close();
          });
        }
      }, 100);
    });
    
    console.log('当前用户标记创建完成，准备添加到地图');
    
    // 将当前用户标记添加到地图
    currentUserMarker.value.setMap(map.value);
    console.log('当前用户标记已添加到地图');
    
    // 确保标记可见
    map.value.setFitView([currentUserMarker.value]);
    
    // 初始设置地图中心为当前用户位置
    map.value.setCenter(position);
    console.log('地图中心已设置为当前用户位置');
  } catch (markErr) {
    console.error('创建标记时出错:', markErr);
  }
};

// 规划路线
const planRoute = (targetUser: UserType) => {
  // 清除现有路线
  clearRoute();
  
  if (!currentUser.value || !currentUser.value.longitude || !currentUser.value.dimension) {
    showToast('当前位置信息不完整，无法规划路线');
    return;
  }
  
  if (!targetUser.longitude || !targetUser.dimension) {
    showToast('目标用户位置信息不完整，无法规划路线');
    return;
  }
  
  // 起点和终点
  const startPoint = [currentUser.value.longitude, currentUser.value.dimension];
  const endPoint = [targetUser.longitude, targetUser.dimension];
  
  // 加载驾车路线规划插件
  window.AMap.plugin(['AMap.Driving'], () => {
    drivingInstance.value = new window.AMap.Driving({
      map: map.value,
      policy: 10 // 使用数值策略，10：时间最短
    });
    
    // 规划路线
    drivingInstance.value.search(startPoint, endPoint, (status, result) => {
      if (status === 'complete') {
        console.log('路线规划成功:', result);
        if (result.routes && result.routes.length > 0) {
          const route = result.routes[0];
          // 显示路线信息
          routeDistance.value = (route.distance / 1000).toFixed(2);
          routeDuration.value = formatDuration(route.time);
          routeTarget.value = targetUser.username || '未知用户';
          showRouteInfo.value = true;
          
          // 缩放地图以适应路线
          if (map.value && route.bounds) {
            map.value.setBounds(route.bounds);
          }
        }
      } else {
        console.error('路线规划失败:', result);
        showToast('路线规划失败，请稍后再试');
      }
    });
  });
};

// 清除路线
const clearRoute = () => {
  if (drivingInstance.value) {
    drivingInstance.value.clear();
  }
  showRouteInfo.value = false;
};

// 关闭路线信息面板
const closeRouteInfo = () => {
  clearRoute();
};

// 格式化时间（秒转为小时和分钟）
const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  } else {
    return `${minutes}分钟`;
  }
};

// 组件挂载时初始化地图和当前用户位置
onMounted(async () => {
  console.log('组件开始挂载');
  try {
    // 等待高德地图API加载完成
    if (!window.AMap) {
      console.log('等待高德地图API加载...');
      await new Promise((resolve) => {
        const checkAMap = setInterval(() => {
          if (window.AMap) {
            clearInterval(checkAMap);
            resolve(true);
          }
        }, 100);
      });
    }
    
    // 初始化地图
    initMap();
    console.log('地图初始化完成');
    
    // 等地图初始化完成后，再加载当前位置
    setTimeout(async () => {
      console.log('setTimeout 开始执行');
      try {
        console.log('准备调用 addOrUpdateCurrentUserMarker');
        await addOrUpdateCurrentUserMarker(); 
        console.log('addOrUpdateCurrentUserMarker 执行完成');
        
        // 只有当用户列表加载完成后才添加其他用户标记
        if (!props.loading && props.userList.length > 0) {
          console.log('准备添加其他用户标记');
          addMarkers();
          console.log('addMarkers 执行完成');
        } else {
          console.log('用户列表未加载完成或为空，跳过添加标记');
        }
      } catch (error) {
        console.error('setTimeout 中发生错误:', error);
        showToast('加载用户位置失败：' + (error instanceof Error ? error.message : String(error)));
      }
    }, 500); 
    console.log('setTimeout 已设置');
    
    // 添加自定义事件监听器，处理地图中心更新
    document.addEventListener('update-map-center', (event: any) => {
      if (!map.value) return;
      
      const { center, userList } = event.detail;
      console.log('收到地图中心更新事件:', center);
      
      if (center && center.length === 2) {
        // 创建边界对象，包含所有用户位置
        const bounds = new window.AMap.Bounds();
        let hasValidMarkers = false;
        
        // 添加所有用户位置到边界
        if (userList && userList.length > 0) {
          userList.forEach((user: UserType) => {
            if (user.longitude && user.dimension) {
              // 转换坐标
              const converted = convertCoordinates(user.longitude, user.dimension);
              const position = new window.AMap.LngLat(converted.lng, converted.lat);
              bounds.extend(position);
              hasValidMarkers = true;
            }
          });
        }
        
        // 如果当前用户标记存在，也添加到边界
        if (currentUserMarker.value) {
          bounds.extend(currentUserMarker.value.getPosition());
          hasValidMarkers = true;
        }
        
        // 如果有有效标记，则调整地图视图
        if (hasValidMarkers) {
          // 设置地图视图以包含所有标记
          map.value.setBounds(bounds, false, [50, 50, 50, 50]);
          console.log('地图视图已更新以显示所有用户');
        } else {
          // 如果没有有效标记，则直接设置地图中心
          map.value.setCenter(new window.AMap.LngLat(center[0], center[1]));
          map.value.setZoom(13); // 设置适当的缩放级别
          console.log('地图中心已设置为:', center);
        }
      }
    });
    
  } catch (error) {
    console.error('组件挂载过程中发生错误:', error);
    showToast('地图初始化失败：' + (error instanceof Error ? error.message : String(error)));
  }
});

// 当组件重新激活时更新当前用户标记（如从其他页面返回）
onActivated(() => {
  console.log('地图组件被激活');
  if (map.value) {
    // 重新获取用户信息并更新标记
    addOrUpdateCurrentUserMarker();
  }
});

// 监听属性变化 - 当用户列表变化时更新其他用户标记
watch(() => props.userList, (newVal) => {
  if (!props.loading && newVal && newVal.length > 0) {
    // 仅更新其他用户标记，不影响当前用户标记
    addMarkers();
  }
}, { deep: true });

// 组件卸载时清除地图
onUnmounted(() => {
  clearMarkers();
  if (currentUserMarker.value) {
    currentUserMarker.value.setMap(null);
  }
  if (map.value) {
    map.value.destroy();
    map.value = null;
  }
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 80vh;
  position: relative;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.map-tips {
  padding: 5px 8px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  font-size: 12px;
  position: absolute;
  top: 10px;
  left: 10px;
  border-radius: 4px;
  z-index: 100;
  animation: fadeOut 5s forwards;
}

@keyframes fadeOut {
  0% { opacity: 1; }
  70% { opacity: 1; }
  100% { opacity: 0; }
}

/* 自定义标记样式 */
:deep(.custom-marker) {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  animation: markerDropIn 0.5s ease-out;
}

:deep(.marker-image) {
  transition: all 0.3s;
}

:deep(.custom-marker:hover .marker-image) {
  transform: scale(1.1);
  box-shadow: 0 0 20px rgba(0,0,0,0.5);
}

:deep(.current-user-marker .marker-image) {
  border-color: #1989fa !important;
  box-shadow: 0 0 20px rgba(25, 137, 250, 0.8) !important;
}

/* 当前用户标记的特殊动画 */
@keyframes pulseMarker {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

:deep(.current-user-marker) {
  animation: pulseMarker 2s infinite ease-in-out;
  z-index: 1000;
}

/* 标记动画 */
@keyframes markerDropIn {
  from {
    opacity: 0;
    transform: translateY(-50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.map-controls {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 100;
}

.locate-btn {
  background-color: white;
  border: none;
  border-radius: 50px;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: all 0.3s;
}

.locate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.locate-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

.locate-icon {
  margin-right: 6px;
  font-size: 18px;
}

.route-info {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  width: 240px;
  z-index: 100;
  overflow: hidden;
  animation: slideIn 0.3s ease-out;
}

.route-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #1989fa;
  color: white;
  font-weight: bold;
}

.route-info-content {
  padding: 10px 15px;
}

.route-info-content p {
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.route-info-content .van-icon {
  margin-right: 8px;
  color: #1989fa;
}

@keyframes slideIn {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style> 